package com.bmd.backgroundmanger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmd.backgroundmanger.entity.Question;
import com.bmd.backgroundmanger.mapper.QuestionMapper;
import com.bmd.backgroundmanger.service.IQuestionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 题目Service实现类 - 简化版（使用JSON存储选项）
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Override
    public List<Question> getQuestionsByCategoryId(Integer categoryId) {
        return baseMapper.selectByCategoryId(categoryId);
    }

    @Override
    public List<Question> getQuestionsByDifficultyLevel(String difficultyLevel) {
        return baseMapper.selectByDifficultyLevel(difficultyLevel);
    }

    @Override
    public List<Question> searchQuestions(String keyword) {
        return baseMapper.searchQuestions(keyword);
    }

    @Override
    public Question getRandomQuestion() {
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        List<Question> questions = list(wrapper);
        
        if (questions.isEmpty()) {
            return null;
        }
        
        Random random = new Random();
        Question question = questions.get(random.nextInt(questions.size()));
        
        System.out.println("获取随机题目: ID=" + question.getQuestionId() + 
                          ", 类型=" + question.getQuestionType() + 
                          ", 选项数量=" + (question.getOptions() != null ? question.getOptions().size() : 0));
        
        return question;
    }

    /**
     * 分页查询题目（简化版）
     */
    public Map<String, Object> getPageData(int page, int size, Integer categoryId, String questionType, String difficultyLevel, String title) {
        Map<String, Object> result = new HashMap<>();
        
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(categoryId != null, Question::getCategoryId, categoryId)
               .eq(StringUtils.hasLength(questionType), Question::getQuestionType, questionType)
               .eq(StringUtils.hasLength(difficultyLevel), Question::getDifficultyLevel, difficultyLevel)
               .like(StringUtils.hasLength(title), Question::getTitle, title)
               .orderByDesc(Question::getCreateTime);

        Page<Question> pageObj = new Page<>(page, size);
        Page<Question> questionPage = this.page(pageObj, wrapper);

        result.put("questions", questionPage.getRecords());
        result.put("total", questionPage.getTotal());
        return result;
    }

    /**
     * 获取题目详情（简化版）
     */
    public Question getQuestionWithOptions(Integer questionId) {
        return this.getById(questionId);
    }

    /**
     * 保存题目（简化版）
     */
    @Transactional
    public boolean saveQuestionWithOptions(Question question) {
        boolean result;
        
        if (question.getQuestionId() == null) {
            // 新增
            question.setCreateTime(LocalDateTime.now());
            result = this.save(question);
            System.out.println("新增题目: ID=" + question.getQuestionId() + 
                              ", 选项数量=" + (question.getOptions() != null ? question.getOptions().size() : 0));
        } else {
            // 更新
            question.setUpdateTime(LocalDateTime.now());
            result = this.updateById(question);
            System.out.println("更新题目: ID=" + question.getQuestionId() + 
                              ", 选项数量=" + (question.getOptions() != null ? question.getOptions().size() : 0));
        }
        
        return result;
    }

    /**
     * 删除题目（简化版）
     */
    @Transactional
    @Override
    public boolean removeById(Integer questionId) {
        return super.removeById(questionId);
    }

    /**
     * 批量删除题目（简化版）
     */
    @Transactional
    @Override
    public boolean removeByIds(List<Integer> questionIds) {
        return super.removeByIds(questionIds);
    }
} 